package thread;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import sound.SoundPlayer;
import util.Base64;
import voice.main.ChatActivity;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

public class TextToSpeechTask extends AsyncTask<String, Void, String> {
	private ChatActivity context;
	public TextToSpeechTask(ChatActivity context) {
		this.context = context;
		Log.v("Constructor", "Begin Constructor");
    }
	
    protected String doInBackground(String... text) {
    	try {
	        HttpPost post = new HttpPost("http://www.ailab.hcmus.edu.vn/tts_bong_demo/Service.asmx?op=TTS");
	        post.setHeader("Content-Type", "text/xml; charset=utf-8");
	        post.setHeader("SOAPAction", "http://tempuri.org/TTS");
	        
	        StringBuffer body = new StringBuffer();
	        body.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
	        body.append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
	        body.append("<soap:Body>");
	        body.append("<TTS xmlns=\"http://tempuri.org/\">");
	        body.append("<czt>" + "truongdeptrai" + "</czt>");
	        body.append("<noidung>" + text[0] + "</noidung>");
	        body.append("</TTS>");
	        body.append("</soap:Body>");
	        body.append("</soap:Envelope>");
	        post.setEntity(new StringEntity(body.toString(), "utf-8"));
	        
	        DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(post);
            String r_entity = EntityUtils.toString(response.getEntity());
            
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new ByteArrayInputStream(r_entity.getBytes("UTF-8")));
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression expr = xpath.compile("//TTSResult");
            NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

            String encodedData = nl.item(0).getTextContent();
            
            String filePath = Environment.getExternalStorageDirectory().toString() + "/Records/testing.wav";
            
            FileOutputStream fileStream = new FileOutputStream(new File(filePath));    	
            byte[] buffer = Base64.decode(encodedData);
            
            fileStream.write(buffer, 0, buffer.length);
            fileStream.close();
            return filePath;
            
		} 
		catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
    	return "Bad Response.";
    }
    protected void onPostExecute(final String filePath) {
    	Log.v("Post", "Post execute");
		if (filePath!="Bad Response.") 
		{
			final SoundPlayer player = new SoundPlayer(context);
			NotifyingThread playingThread = new NotifyingThread() {
	    		public void doRun() {
	    			player.play(filePath);
	    		}
	    		public void doStop() {
	    			player.stop();
	    		}
				public void doCancel() {
					player.stop();
					
				}
			};
			playingThread.start();
		}
    }

}
